import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'umi';
import { get as getPath } from 'object-path';
import { formatMessage } from 'umi';
import { QuickForm } from 'vv-frontend-components';
import PageRouter from '@/components/PageRouter/PageRouter';
import { Card, Empty, Form, Button, Row, Col } from 'antd';
import QueryPage from '@/components/QueryPage';
import { getQuerylist } from '@/services/recruitStat/talentPool';
import { getTypeList } from '@/services/attendance/overtime';
import Locale from '@/utils/locale';
import { SelectForm } from '@/components/UserForm';
import ReactEcharts from '@/components/Echarts';
import colors from '@/theme';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './index.less';
import { everyEmpty } from './utils';

const { locale } = new Locale('stat.overtime');

/** 招聘效率分析 */
const TalentPool = ({ form, talentPool1, loading, dispatch, location }) => {
    const { data } = talentPool1;
    const user = localStorage.getItem('user');
    const localCompanyId = user ? JSON.parse(user).companyId : undefined;
    const isFirstRun = useRef(true);
    const [observeType, setObserveType] = useState(null);
    const [observeSchedule, setObserveSchedule] = useState(null);
    const [recruitName, setRecruitName] = useState('招聘职位效率分析');
    const [recruitNameTmp, setRecruitNameTmp] = useState('招聘职位效率分析');
    const handleSubmit = name => {
        form.validateFields(async (err, values) => {
            if (!err) {
                dispatch({
                    type: 'talentPool1/getTalentPool',
                    payload: values.recruitCode
                }).then(() => {
                    setRecruitName(name || recruitNameTmp);
                });
            }
        });
    };
    const getOption = () => ({
        grid: {
            top: '5%',
            left: '-50px',
            right: '20%',
            bottom: '10%',
            containLabel: true
        },
        xAxis: {
            type: 'value'
        },
        yAxis: {
            type: 'category',
            data: data.map(item => item.name).reverse(),
            axisLine: { show: false },
            axisLabel: {
                interval: 0,
                margin: 110,
                textStyle: {
                    align: 'left',
                    baseline: 'middle'
                }
            },
            axisTick: {
                show: false
            }
        },
        series: [
            {
                type: 'bar',
                data: data
                    .map((item, index) => ({
                        ...item,
                        itemStyle: {
                            normal: {
                                color: colors[index]
                            }
                        }
                    }))
                    .reverse(),
                label: {
                    normal: {
                        show: true,
                        position: 'right',
                        color: 'rgba(0,0,0,0.65)'
                    }
                },
                barWidth: 21
            }
        ]
    });
    const getLegend = () => ({
        legend: {
            type: 'scroll',
            data: data.map(item => item.name)
        },
        series: [
            {
                name: '访问来源',
                type: 'pie',
                radius: '0%',
                tooltip: {
                    show: false
                },
                center: ['50%', '60%'],
                data,
                label: {
                    normal: {
                        show: false
                    }
                },
                animation: false
            }
        ]
    });
    const config = [
        {
            field: 'postType',
            label: '类型：',
            key: 'id',
            component: (
                <SelectForm
                    params={{ dictCode: 'postType' }}
                    requireParam={['dictCode']}
                    getData={params =>
                        getTypeList(params).then(res => {
                            if (res && res.code === 10000 && res.data) {
                                const newData = [
                                    {
                                        dictValue: 'empty',
                                        dictName: '全部'
                                    }
                                ];
                                newData.push(...res.data);
                                setObserveType(getPath(newData, '0.dictValue', ''));
                                return newData || [];
                            }
                            return [];
                        })
                    }
                    fieldsName={{
                        selectValue: 'dictValue',
                        selectTitle: 'dictName'
                    }}
                    selectProps={{
                        placeholder: '请选择类型',
                        style: { minWidth: 150 }
                    }}
                    onChange={e => {
                        form.setFieldsValue({ recruitCode: null });
                        setObserveType(e);
                    }}
                />
            ),
            config: {
                rules: [{ required: true, message: '请选择类型' }],
                initialValue: observeType
            }
        },
        {
            field: 'recruitScheduleType',
            label: '招聘进度：',
            key: 'id',
            component: (
                <SelectForm
                    params={{ dictCode: 'recruitScheduleType' }}
                    requireParam={['dictCode']}
                    getData={params =>
                        getTypeList(params).then(res => {
                            if (res && res.code === 10000 && res.data) {
                                const newData = [
                                    {
                                        dictValue: 'empty',
                                        dictName: '全部'
                                    }
                                ];
                                newData.push(...res.data);
                                setObserveSchedule(getPath(newData, '0.dictValue', ''));

                                return newData || [];
                            }
                            return [];
                        })
                    }
                    selectProps={{
                        style: { minWidth: 250 },
                        placeholder: '请选择招聘进度'
                    }}
                    fieldsName={{
                        selectValue: 'dictValue',
                        selectTitle: 'dictName'
                    }}
                    onChange={e => {
                        form.setFieldsValue({ recruitCode: null });
                        setObserveSchedule(e);
                    }}
                />
            ),
            config: {
                rules: [{ required: true, message: '请选择招聘进度' }],
                initialValue: observeSchedule
            }
        },
        {
            field: 'recruitCode',
            label: '招聘职位：',
            key: 'recruitCode',
            component: (
                <SelectForm
                    params={{
                        postType: observeType,
                        recruitSchedule: observeSchedule,
                        companyId: localCompanyId
                    }}
                    requireParam={['postType', 'recruitSchedule']}
                    onChange={(e, o) => {
                        setRecruitNameTmp(getPath(o, 'props.title'));
                    }}
                    getData={params =>
                        getQuerylist({
                            postType: params.postType === 'empty' ? '' : params.postType,
                            recruitSchedule: params.recruitSchedule === 'empty' ? '' : params.recruitSchedule,
                            companyId: localCompanyId
                        }).then(res => {
                            if (res && res.code === 10000 && res.data) {
                                // 第一次时默认选择第一项 初始化页面
                                if (isFirstRun.current) {
                                    isFirstRun.current = false;
                                    form.setFieldsValue({
                                        recruitCode: getPath(res, 'data.0.recruitCode', '')
                                    });
                                    setRecruitNameTmp(getPath(res, 'data.0.recruitName', ''));
                                    handleSubmit(getPath(res, 'data.0.recruitName', ''));
                                }
                                return res.data || [];
                            }
                            return [];
                        })
                    }
                    fieldsName={{
                        selectValue: 'recruitCode',
                        selectTitle: 'recruitName'
                    }}
                    selectProps={{
                        placeholder: '请选择应聘职位',
                        style: { minWidth: 300, marginRight: '20px' }
                    }}
                />
            ),
            config: {
                initialValue: null,
                rules: [{ required: true, message: '请选择应聘职位' }]
            }
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];
    const headStyle = {
        fontSize: '16px',
        lineHeight: '22px'
    };
    useEffect(
        () => () => {
            dispatch({
                type: 'talentPool1/clear'
            });
        },
        []
    );
    const { pathname } = location;
    const tabType = pathname.includes('office') ? 'recruit' : 'recruitStat';
    return (
        <PageHeaderWrapper>
            <PageRouter type={tabType}>
                <QueryPage
                    style={{ overflow: 'hidden' }}
                    className={styles.queryWn}
                    background="transparent"
                    form={
                        <Form
                            layout="inline"
                            onSubmit={e => {
                                e.preventDefault();
                                handleSubmit();
                            }}
                        >
                            <Card bordered={false} title="招聘效率分析" headStyle={headStyle}>
                                <QuickForm form={form} config={config} />
                            </Card>
                        </Form>
                    }
                />
                <div className={styles.slideDiv}>
                    <Card
                        bordered={false}
                        title={recruitName}
                        loading={loading}
                        headStyle={{
                            border: 'none'
                        }}
                        className={styles.cardTitle}
                    >
                        {!everyEmpty(data) ? (
                            <React.Fragment>
                                <Row>
                                    <Col span={24}>
                                        <ReactEcharts option={getOption()} />
                                    </Col>
                                    <Col span={24}>
                                        <ReactEcharts
                                            style={{
                                                height: 30
                                            }}
                                            option={getLegend()}
                                        />
                                    </Col>
                                </Row>
                            </React.Fragment>
                        ) : (
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description={formatMessage({
                                    id: 'stat.name.zwsj'
                                })}
                            />
                        )}
                    </Card>
                </div>
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ talentPool1, loading }) => ({
        talentPool1,
        loading: loading.models.talentPool1
    }))(Form.create()(TalentPool))
);
